package com.atguigu.springcloud.alibaba.service.impl;

import cn.hutool.core.util.IdUtil;
import com.atguigu.springcloud.alibaba.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

@Service
public class PaymentServiceImpl implements PaymentService {


    // --------  服务降级 ---------
    /**
     * 正常访问，肯定OK
     * @param id
     * @return
     */
    public String paymentInfo_OK(Integer id){
        return "线程池：" + Thread.currentThread().getName() + "  paymentInfo_OK, id:  " + id + "\t" + "O(∩_∩)O哈哈";
    }

    /**
     * 超时访问演示降级
     * fallbackMethod ：兜底的方法名
     * HystrixProperty：规定3秒钟走正常的业务逻辑（设置自身调用超时时间的峰值，峰值内可以正常运行）
     *              超过3秒出错(超时)走兜底方法
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
    })
    public String paymentInfo_TimeOut(Integer id){
        // 暂停timeNumber秒钟线程
        try {
            TimeUnit.MILLISECONDS.sleep(3000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        return "线程池：" + Thread.currentThread().getName() + " , id:  " + id + "\t" + "O(∩_∩)O哈哈" + "耗时(秒)";
    }

    /**
     * 上面出了问题，我来兜底
     * @param id
     * @return
     */
    public String paymentInfo_TimeOutHandler(Integer id){
//        return "/(T.T)/调用支付接口超时或异常：\t" + "\t 当前线程池名字" + Thread.currentThread().getName();
        return "线程池：" + Thread.currentThread().getName() + "  系统繁忙或运行报错，请稍后再试, id:  " + id +"\t"+ "/(ㄒoㄒ)/~~";
    }


    // --------  服务熔断 --------
    // 查看官网获取配置
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),// 是否开启断路器
            // 假设再10秒的时间范围内，10次请求次数里面，有60%以上是失败的，达到前面的阈值，断路器就要起作用（开启）
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),// 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),// 时间窗口期（时间范围）
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),// 失败率达到多少后跳闸
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id){
        if (id < 0){
            throw new RuntimeException("******id 不能为负数");
        }
        // 查看 https://hutool.cn/ 生成的是不带-的字符串
        String serialNumber = IdUtil.simpleUUID(); // 等价与UUID.randomUUID().toString()

        return Thread.currentThread().getName() + "\t" + "调用成功，流水号：" + serialNumber;
    }

    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){
        return "id 不能负数，请稍后再试，/(ㄒoㄒ)/~~ id：" + id;
    }

}


